package algorithms.dynamicProgram;

public class LeetCode_152 {

    public static void main(String[] args) {
        int[] ints = {-2,-3, -4};
        System.out.println(maxProduct(ints));

    }

    public static int maxProduct(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }
        int min = nums[0];
        int max = nums[0];
        int res = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if(nums[i] < 0){
                int temp = max ;
                max = min;
                min = max;
            }
            max = Math.max(max * nums[i], nums[i]);
            min = Math.min(min * nums[i], nums[i]);

            if (res < max) {
                res = max;
            }
        }
        return res;
    }

    public static int maxProduct1(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }
        int[][] dp = new int[nums.length][2];
        dp[0][0] = nums[0];
        dp[0][1] = nums[0];
        int max = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > 0) {
                dp[i][0] = Math.max(dp[i - 1][0] * nums[i], nums[i]);
                dp[i][1] = Math.min(dp[i - 1][1] * nums[i], nums[i]);
            } else {
                dp[i][0] = Math.max(dp[i - 1][1] * nums[i], nums[i]);
                dp[i][1] = Math.min(dp[i - 1][0] * nums[i], nums[i]);
            }
            if (dp[i][0] > max) {
                max = dp[i][0];
            }
        }
        return max;
    }
}
